package cuit.lh.remotecontrol;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 启动界面
 *
 * @author lh
 */
public class RemoteAssistance extends JFrame {

    private static final long serialVersionUID = -502914245090231502L;
    private JRadioButton serverJRB;
    private JRadioButton clientJRB;
    private ButtonGroup btnGroup;
    private JLabel infoJL;
    private JButton okBtn;
    private JFileChooser fileChooser;
    private JButton sendButton;
    private JButton receiveButton;
    private String serverIp;

    public RemoteAssistance() {

        initComponent();
        registerListeners();

    }

    private void registerListeners() {
        okBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (serverJRB.isSelected()) {
                    createServer();
                } else if (clientJRB.isSelected()) {
                    createClient();
                }
            }

            private void createClient() {
                JFrame frame = new JFrame("远程控制");
                serverIp = JOptionPane.showInputDialog("请输入远程连接IP");
                while (serverIp.isEmpty()) {
                    serverIp = JOptionPane.showInputDialog("请输入远程连接IP");
                }
                while (!StringUtil.isValidIP(serverIp)) {
                    serverIp = JOptionPane.showInputDialog("请输入合法IP");
                }

                String port = JOptionPane.showInputDialog("输入远程连接端口");
                while (port.isEmpty()) {
                    port = JOptionPane.showInputDialog("请输入远程连接端口");
                }
                while (!StringUtil.isValidPort(port)) {
                    port = JOptionPane.showInputDialog("请输入合法端口");
                }
                JOptionPane.showMessageDialog(null, "开始远程连接!");

                Client client = new Client(serverIp, Integer.parseInt(port));
                JScrollPane jsp = new JScrollPane(client, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                frame.add(jsp);
                frame.setDefaultCloseOperation(3);
                frame.setSize(800, 600);
                frame.setVisible(true);
            }

            private void createServer() {
                Server server;
                try {

                    String ip = JOptionPane.showInputDialog("请输入本地IP(" + InetAddress.getLocalHost().getHostAddress() + ")");
//					String ip = JOptionPane.showInputDialog("请输入本地IP");
                    if ("null".equals(ip)) {
                        System.exit(0);
                    }
                    if (ip.isEmpty()) ip = InetAddress.getLocalHost().getHostAddress();
                    while (ip.isEmpty() || !StringUtil.isValidIP(ip)) {
                        if (ip.isEmpty()) ip = JOptionPane.showInputDialog("请输入本地IP");
                        else ip = JOptionPane.showInputDialog("请输入合法IP");
                    }
                    String port = JOptionPane.showInputDialog("请输入本地端口");
//					String port = "8899";
                    if ("null".equals(port)) {
                        System.exit(0);
                    }
                    while (port.isEmpty() || !StringUtil.isValidPort(port)) {
                        if (port.isEmpty()) port = JOptionPane.showInputDialog("请输入本地端口");
                        else port = JOptionPane.showInputDialog("请输入合法端口");
                    }
                    while (StringUtil.isPortUsed(Integer.parseInt(port))) {
                        port = JOptionPane.showInputDialog("端口被占用,请输入其他端口");
                    }
                    server = new Server(ip, Integer.parseInt(port));
                    server.start();
                    JFrame frame = new JFrame("远程连接被控制端");
                    frame.add(server);
                    frame.setSize(300, 85);
                    frame.setDefaultCloseOperation(3);
                    frame.setVisible(true);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (AWTException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 初始化界面
     */
    private void initComponent() {
        infoJL = new JLabel("请选择：");
        btnGroup = new ButtonGroup();
        serverJRB = new JRadioButton("被控制者");
        serverJRB.setSelected(true);
        clientJRB = new JRadioButton("控制端");
        btnGroup.add(serverJRB);
        btnGroup.add(clientJRB);
        okBtn = new JButton("确定");
        // 创建文件选择器
        fileChooser = new JFileChooser();

        // 创建发送按钮
        sendButton = new JButton("Send File");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int returnVal = fileChooser.showOpenDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    serverIp = "192.168.100.103";
                    int port = 8890;
                    sendFile(file, serverIp, port);
                }

            }
        });
        // 创建接收按钮
        receiveButton = new JButton("receive File");
        receiveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                FileServer fileServer = new FileServer();
                try {
                    fileServer.receive();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
            }
        });
        setLayout(new FlowLayout());
        this.add(infoJL);
        this.add(serverJRB);
        this.add(clientJRB);
        this.add(okBtn);
        this.add(sendButton);
        this.add(receiveButton);
        JLabel label = new JLabel("Remote control program");
        this.add(label);
    }

    /**
     * 发送文件功能
     *
     * @param file
     * @param server
     * @param port
     */
    private void sendFile(File file, String server, int port) {
        try (Socket socket = new Socket(server, port);
             PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {

            writer.println(file.getName());
            writer.flush(); // 确保文件名被发送

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                socket.getOutputStream().write(buffer, 0, bytesRead);
            }
            socket.getOutputStream().flush(); // 确保文件内容被发送

            System.out.println("文件发送成功.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void start() {
        RemoteAssistance rAssistance = new RemoteAssistance();
        rAssistance.setTitle("远程控制程序");
        rAssistance.setDefaultCloseOperation(3);
        rAssistance.setSize(320, 240);
        rAssistance.setVisible(true);
    }

}